<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Common\Internal;
use App\Models\LoanApplication;
use App\Models\LoanCreditProvident;
use App\Models\LoanMortgageCar;
use App\Models\LoanMortgageHouse;
use App\Models\LoanMortgageTax;
use App\Models\UserTicketLog;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\DB;

class LoanApplicationController extends BaseController
{

    protected $publicKey = 1322434504065251;

    public function checkStatus(Request $request)
    {
        $user = $request->user();
        if(!$user){
            return response()->json([
                'code' => -1,
                'msg' => '还未登录，无法使用筛选',
                'data' => []
            ]);
        }
        if(!UserTicketLog::where('user_id', $user->id)->where('category',1)->exists()){
            return response()->json([
                'code' => -1,
                'msg' => '用户充值后才能使用筛选',
                'data' => []
            ]);
        }

        if($user->ticket < 50){
            return response()->json([
                'code' => -1,
                'msg' => '金币不足，无法使用筛选',
                'data' => []
            ]);
        }
        return response()->json([
            'code' => 200,
            'msg' => '',
            'data' => []
        ]);
    }


    public function addNumber()
    {
        $LoanApplication = LoanApplication::whereNull('number')->get()->toArray();
        foreach ($LoanApplication as $value){
            $re_data['number'] = 'rysk'.time().rand(10000,99999);
            LoanApplication::where('id', $value['id'])->update($re_data);
        }
    }

    public function delOrder()
    {
        $uniqueRecords = DB::table('loan_application')
            ->select('mobile', DB::raw('MIN(id) as id')) // 假设每条记录都有一个唯一的ID
            ->groupBy('mobile')
            ->havingRaw('COUNT(*) > 1'); // mobile字段有重复记录

        // 获取所有符合条件的mobile字段和对应的代表记录ID
        $uniqueRecords = $uniqueRecords->get()->pluck('id');


        $list = [];
        foreach ($uniqueRecords as $v){
            $list[] = $v;
        }
        // 删除mobile字段重复且user_id为空的数据，但保留上面查询得到的ID对应的记录
        DB::table('loan_application')
            ->where('user_id',0) // user_id为空
            ->whereIn('id', $list) // 不包含代表记录的ID
            ->delete(); // 执行删除操作

    }


   public function addLoan(Request $request)
   {
       $data = $request->all();
       $sign = $data['data'];
       $data = self::decryptECB($sign);
       if(!$data){
           return response()->json([
               'code' => -1,
               'msg' => '解密失败!',
               'data' => []
           ]);
       }


       $data = json_decode($data,true);
       if(LoanApplication::where('mobile',$data['mobile'])->where('created_at','>',date('Y-m-d H:i:s',strtotime("-1 day")))->exists()){
           return response()->json([
               'code' => -1,
               'msg' => '手机号重复!',
               'data' => []
           ]);
       }
       if($data['amount']<50000){
           $data['amount'] = 50000;
       }
       $re_data = [];

       $number = 'rysk';
       if(strpos($data['custom_field'],'车') !== false){
           $number = $number.'cd';
       }
       if(strpos($data['custom_field'],'公积金') !== false){
           $number = $number.'ggj';
       }
       if(strpos($data['custom_field'],'房') !== false){
           $number = $number.'fd';
       }
       if(strpos($data['custom_field'],'企业') !== false) {
           $number = $number . 'qyz';
       }
       $re_data['number'] = $number.time().rand(10000,99999);
       $re_data['name'] = $data['name'];
       $re_data['mobile'] = $data['mobile'];
       $re_data['province'] = $data['city'];
       $re_data['has_house'] = $data['has_house'];
       $re_data['has_car'] = $data['has_car'];
       $re_data['has'] = $data['has'];
       $re_data['yingyezhizhao'] = $data['yingyezhizhao'];
       $re_data['channel_name'] = $data['channel_name'];
       $re_data['has_gongjijin'] = $data['has_gongjijin'];
       $re_data['zhima'] = $data['zhima'];
       $re_data['city'] = '';
       $re_data['district'] = '';
       $re_data['addr'] = '';
       $re_data['user_id'] = 0;
       $re_data['org_root'] = 200;
       $re_data['org_code'] = 200;
       $re_data['source'] = 2;
       $re_data['status'] = 0;
       $re_data['price_ticket'] = 1;
       $re_data['apply_at'] = $data['apply_at'];
       $re_data['amount_start'] = $data['amount'];
       $re_data['amount_end'] = $data['amount'];
       $re_data['category'] = 'general';
       $re_data['category_type'] = $data['category_type'];
       $re_data['custom_field'] = $data['custom_field'];
       $re_data['created_at'] = date('Y-m-d H:i:s',time());
       DB::beginTransaction();
       try {
           $order_id = LoanApplication::insertGetId($re_data);
           if(strpos($data['custom_field'],'咨询') !== false){
               $data = self::getLoanOther($data);
           }
           if(strpos($data['custom_field'],'车') !== false){
               self::insertLoanMortgageCar($order_id,$data);
           }
           if(strpos($data['custom_field'],'公积金') !== false){
               self::insertLoanCreditProvident($order_id,$data);
           }
           if(strpos($data['custom_field'],'房') !== false){
               self::insertLoanMortgageHouse($order_id,$data);
           }
           if(strpos($data['custom_field'],'企业') !== false){
               self::insertLoanMortgageTax($order_id,$data);
           }
           DB::commit();
           return response()->json([
               'code' => 200,
               'msg' => '请求成功',
               'data' => []
           ]);
       }catch (\Exception $exception){
           DB::rollBack();
           return response()->json([
               'code' => -1,
               'msg' => $exception->getMessage(),
               'data' => []
           ]);
       }

   }

   public function getLoanOther($data)
   {
       if(strpos($data['custom_field'],'车') !== false){
           $LoanMortgageCar = LoanMortgageCar::inRandomOrder()->first()->toArray();
           $data['car_state'] = $LoanMortgageCar['info'];
           $data['car_price_estimation'] = $LoanMortgageCar['car_price_estimation'];
           $data['car_model'] = $LoanMortgageCar['car_model'];
       }
       if(strpos($data['custom_field'],'房') !== false){
           $LoanMortgageHouse = LoanMortgageHouse::inRandomOrder()->first()->toArray();
           $data['house_model'] = $LoanMortgageHouse['type'];
           $data['house_state'] = $LoanMortgageHouse['has_certificate'];
           $data['house_price_estimation'] = $LoanMortgageHouse['latest_estimated'];
       }
       if(strpos($data['custom_field'],'公积金') !== false){
           $LoanCreditProvident = LoanCreditProvident::inRandomOrder()->first()->toArray();
           $data['gongjijin_company_name'] = $LoanCreditProvident['company_name'];
           $data['gongjijin_wages_payment_mode'] = $LoanCreditProvident['pay_method'];
           $data['gongjijin_wages'] = $LoanCreditProvident['month_salary'];
           $data['gongjijin_year'] = $LoanCreditProvident['provident_age'];
           $data['gongjijin_price'] = $LoanCreditProvident['month_provident'];
       }
       if(strpos($data['custom_field'],'企业') !== false){
           $LoanMortgageTax = LoanMortgageTax::inRandomOrder()->first()->toArray();
           $data['yingyezhizhao_company_name'] = $LoanMortgageTax['company_name'];
           $data['yingyezhizhao_annal_tax'] = $LoanMortgageTax['annal_tax'];
           $data['yingyezhizhao_annal_turnover'] = $LoanMortgageTax['annal_turnover'];
           $data['yingyezhizhao_company_age'] = $LoanMortgageTax['company_age'];
           $data['yingyezhizhao_is_legal_person'] = $LoanMortgageTax['is_legal_person'];
       }
       return $data;
   }


    public function insertLoanMortgageTax($order_id,$data)
    {
        $re_providentr_data = [];
        $re_providentr_data['loan_id'] = $order_id;
        $re_providentr_data['company_name'] = Internal::getDataPQ($data['yingyezhizhao_company_name']);
        $re_providentr_data['annal_tax'] = Internal::getDataPQ($data['yingyezhizhao_annal_tax']);
        $re_providentr_data['annal_turnover'] = Internal::getDataPQ($data['yingyezhizhao_annal_turnover']);
        $re_providentr_data['company_age'] = Internal::getDataPQ($data['yingyezhizhao_company_age']);
        $re_providentr_data['is_legal_person'] = Internal::getDataPQ($data['yingyezhizhao_is_legal_person']);
        LoanMortgageTax::insert($re_providentr_data);
    }

    public function insertLoanMortgageHouse($order_id,$data)
    {
        $re_providentr_data = [];
        $re_providentr_data['loan_id'] = $order_id;
        $re_providentr_data['type'] = Internal::getDataPQ($data['house_model']);
        $re_providentr_data['has_certificate'] = Internal::getDataPQ($data['house_state']);
        $re_providentr_data['latest_estimated'] = Internal::getDataPQ($data['house_price_estimation']);
        $re_providentr_data['ownership'] = '-';
        LoanMortgageHouse::insert($re_providentr_data);
    }
    public function insertLoanCreditProvident($order_id,$data)
    {
        $re_providentr_data = [];
        $re_providentr_data['loan_id'] = $order_id;
        $re_providentr_data['company_name'] = Internal::getDataPQ($data['gongjijin_company_name']);//上班公司名字全称
        $re_providentr_data['pay_method'] = Internal::getDataPQ($data['gongjijin_wages_payment_mode']);//工资发放模式
        $re_providentr_data['month_salary'] = Internal::getDataPQ($data['gongjijin_wages']);//每月工资多少
        $re_providentr_data['provident_age'] = Internal::getDataPQ($data['gongjijin_year']);//已购买公积金多少年
        $re_providentr_data['month_provident'] = Internal::getDataPQ($data['gongjijin_price']);//每月公积金缴存
        $re_providentr_data['social_insurance_age'] = Internal::getDataPQ('-');//已购买社保多少年
        $re_providentr_data['month_social_insurance'] = Internal::getDataPQ('-');//每个月社保缴费多少
        LoanCreditProvident::insert($re_providentr_data);
    }

   public function insertLoanMortgageCar($order_id,$data)
   {
       $re_car_data = [];
       $re_car_data['car_age'] = 0;
       $re_car_data['buy_price'] = 0;
       $re_car_data['car_no'] = '-';
       $re_car_data['created_at'] = date('Y-m-d H:i:s',time());
       $re_car_data['loan_id'] = $order_id;
       $re_car_data['car_model'] = Internal::getDataPQ($data['car_model']);
       $re_car_data['car_price_estimation'] = Internal::getDataPQ($data['car_price_estimation']);
       $re_car_data['info'] = Internal::getDataPQ($data['car_state']);
       LoanMortgageCar::insert($re_car_data);
   }

    public function decryptECB($content) {
        $aes = 'AES-256-ECB';
        if(strlen($this->publicKey)==32){
            $aes = 'AES-256-ECB';
        }
        if(strlen($this->publicKey)==16){
            $aes = 'AES-128-ECB';
        }
        return  openssl_decrypt(base64_decode($content), $aes,$this->publicKey, OPENSSL_RAW_DATA);

    }


    public function ScheduledAllocateTimeUpdate()
    {
        $time = date('Y-m-d H:i:s',strtotime(date('Y-m-d',time())));

        $LoanApplication = LoanApplication::where('apply_at','<',$time)->where('user_id',0)->get()->toArray();

        foreach ($LoanApplication as $value) {
            $time = date('Y-m-d H:i:s',time() - rand(1,21600));
            LoanApplication::where('id',$value['id'])->update(['apply_at'=>$time]);
        }

    }
}
